import { DeviceDeviceService } from './../device/service/device';
import { CoolEvent, Event } from '@cool-midway/core';
import { Inject } from '@midwayjs/core';
import { PluginService } from '../plugin/service/info';
import { EVENT_PLUGIN_READY } from '../plugin/service/center';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { DeviceDeviceEntity } from '../device/entity/device';
import { Repository } from 'typeorm';
import { OrderOrderEntity } from '../order/entity/order';

/**
 * MQTT事件
 */
@CoolEvent()
export class DemoQmttEvent {
  @Inject()
  pluginService: PluginService;

  @InjectEntityModel(DeviceDeviceEntity)
  DeviceDeviceEntity: Repository<DeviceDeviceEntity>;

  @InjectEntityModel(OrderOrderEntity)
  OrderOrderEntity: Repository<OrderOrderEntity>;

  /**
   * 插件已就绪
   */
  @Event(EVENT_PLUGIN_READY)
  async pluginReady(keyName: string) {
    // 如果是mqtt插件
    if (!keyName || keyName == 'mqtt') {
      // 获取插件实例
      const instance = await this.pluginService.getInstance('mqtt');

      // 监听是否连接成功
      instance.onEvent('connect', () => {
        console.log('connect');
        // 连接成功后订阅消息
        instance.subscribe('Device/#');
        instance.subscribe('Service/#');
      });
      // // 监听消息
      instance.onEvent('message', (topic, msg) => {
        const _device = JSON.parse(msg.toString())?.device;

        console.log('MQtt消息回来了啊啊啊=>', JSON.parse(msg.toString()));

        if (topic.includes('Device') && _device) {
          const _msg = JSON.parse(msg.toString());

          if (_msg?.res === 'OK') {
            return this.OrderOrderEntity.update(
              { orderNo: _msg?.num },
              { isComplete: true }
            );
          }

          /* 该设备有心跳，证明其是在线的 */
          try {
            this.DeviceDeviceEntity.update(
              { deviceNo: _device },
              { deviceStatus: 1, lastOnlineTime: new Date().getTime() / 1000 }
            );
          } catch (error) {}
        }
        // else if (topic.includes('Service')) {
        //   const orderUuid = JSON.parse(msg.toString())?.num;

        //   console.log('orderUuid', orderUuid);

        //   // 如果存在，证明该订单已经投币完成
        //   if (orderUuid) {
        //     // 更新对应的订单状态
        //     this.OrderOrderEntity.update(
        //       { orderNo: orderUuid },
        //       { isComplete: true }
        //     );
        //   }
        // }
      });
    }
  }
}
